package san.java.day10;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

/**
 * TreeSet是SortedSet接口的实现类,TreeSet可以确保集合处于排序状态.
 *  TreeSet必须放入相同类的对象. (默认会进行排序), 否则可能会发生类型转换异常
 *
 *  继承关系:
 *      TreeSet --> NavigableSet接口 --> SortedSet接口 --> Set接口 --> Collection接口
 *
 *  TreeSet支持两种排序方法:
 *      1. 自然排序
 *      2. 定制排序
 *      默认采用自然排序
 */

public class TreeSet_05 {

    public static void main(String[] args) {
        Set<Integer> treeSet = new TreeSet<Integer>();

        treeSet.add(5);
        treeSet.add(1);
        treeSet.add(2);
        treeSet.add(6);

        System.out.println(treeSet);

        Set<Person> personSet = new TreeSet<Person>();
        Person p1 = new Person(26, "san");
        Person p2 = new Person(25, "lisi");
        Person p3 = new Person(24, "wangwu");
        personSet.add(p1);
        personSet.add(p2);
        personSet.add(p3);

        System.out.println(personSet);

    }

}

class Person implements Comparable<Person> {
    int age;
    String name;

    public Person() {

    }

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public int compareTo(Person o) {
        if (this.age > o.age)
            return 1;
        else if (this.age < o.age)
            return -1;
        return 0;
    }
}
